import React, { useEffect, useRef } from "react";
import styled from "@emotion/styled";
import { motion, AnimatePresence } from "framer-motion";
import { FiX } from "react-icons/fi";
import {
  zIndex,
  duration,
  easing,
  motionEasing,
  radius,
  spacing,
} from "../utils/design-tokens";

// 样式定义
const ModalBackdrop = styled(motion.div)`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: ${zIndex.modalBackdrop};
  padding: ${spacing["4"]};

  @media (max-width: 768px) {
    padding: ${spacing["2"]};
  }
`;

const ModalContent = styled(motion.div)`
  background-color: var(--bg-primary);
  border-radius: ${radius.xl};
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1),
    0 10px 10px -5px rgba(0, 0, 0, 0.04);
  width: 100%;
  max-width: 480px;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  z-index: ${zIndex.modal};

  [data-theme="dark"] & {
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.3),
      0 10px 10px -5px rgba(0, 0, 0, 0.2);
  }

  @media (max-width: 768px) {
    max-width: none;
  }
`;

const ModalHeader = styled.div`
  padding: ${spacing["5"]} ${spacing["6"]};
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  justify-content: space-between;

  @media (max-width: 768px) {
    padding: ${spacing["4"]} ${spacing["5"]};
  }
`;

const ModalTitle = styled.h3`
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-primary);
  line-height: 1.4;

  @media (max-width: 768px) {
    font-size: 1.125rem;
  }
`;

const ModalBody = styled.div`
  padding: ${spacing["6"]};
  color: var(--text-secondary);
  font-size: 1rem;
  line-height: 1.6;
  word-break: break-word;

  @media (max-width: 768px) {
    padding: ${spacing["5"]};
  }
`;

const ModalFooter = styled.div`
  padding: ${spacing["4"]} ${spacing["6"]};
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: ${spacing["3"]};

  @media (max-width: 768px) {
    padding: ${spacing["3"]} ${spacing["5"]};
    gap: ${spacing["2"]};
  }
`;

const Button = styled.button<{ $variant?: "primary" | "danger" | "default" }>`
  padding: 0.5rem 1rem;
  border-radius: ${radius.md};
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all ${duration.fast}ms ${easing.ease};
  outline: none;
  font-family: inherit;
  min-height: 2.5rem;

  ${({ $variant }) => {
    if ($variant === "primary") {
      return `
        background-color: var(--accent-color);
        color: white;
        border: 2px solid var(--accent-color);
        
        &:hover {
          background-color: var(--accent-color-hover);
          border-color: var(--accent-color-hover);
          transform: translateY(-1px);
        }
      `;
    } else if ($variant === "danger") {
      return `
        background-color: var(--error-color);
        color: white;
        border: 2px solid var(--error-color);
        
        &:hover {
          background-color: #d32f2f;
          border-color: #d32f2f;
          transform: translateY(-1px);
        }
      `;
    } else {
      return `
        background-color: var(--bg-secondary);
        color: var(--text-primary);
        border: 2px solid var(--border-color);
        
        &:hover {
          background-color: var(--bg-tertiary);
          border-color: var(--accent-color-alpha);
          transform: translateY(-1px);
        }
      `;
    }
  }}

  &:active {
    transform: translateY(0);
  }

  &:focus-visible {
    outline: 2px solid var(--accent-color);
    outline-offset: 2px;
  }

  @media (max-width: 768px) {
    padding: 0.45rem 0.875rem;
    font-size: 0.875rem;
  }
`;

const CloseButton = styled.button`
  background: none;
  border: none;
  color: var(--text-tertiary);
  cursor: pointer;
  padding: ${spacing["1"]};
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: ${radius.full};
  transition: all ${duration.fast}ms ${easing.ease};

  &:hover {
    background-color: var(--bg-tertiary);
    color: var(--text-primary);
  }

  &:active {
    transform: scale(0.95);
  }
`;

// 组件接口
export interface ConfirmDialogProps {
  title: string;
  message: React.ReactNode;
  open: boolean;
  confirmText?: string;
  cancelText?: string;
  confirmVariant?: "primary" | "danger";
  onConfirm: () => void;
  onCancel: () => void;
}

// 确认对话框组件
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
  title,
  message,
  open,
  confirmText = "确认",
  cancelText = "取消",
  confirmVariant = "primary",
  onConfirm,
  onCancel,
}) => {
  const modalRef = useRef<HTMLDivElement>(null);

  // 监听ESC键
  useEffect(() => {
    if (!open) return;

    const handleEsc = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onCancel();
      }
    };

    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [open, onCancel]);

  // 处理点击背景
  const handleBackdropClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onCancel();
    }
  };

  // 阻止内容点击事件冒泡
  const handleContentClick = (e: React.MouseEvent) => {
    e.stopPropagation();
  };

  return (
    <AnimatePresence>
      {open && (
        <ModalBackdrop
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{
            duration: duration.fast / 1000,
            ease: motionEasing.ease,
          }}
          onClick={handleBackdropClick}
        >
          <ModalContent
            ref={modalRef}
            initial={{ opacity: 0, scale: 0.95, y: 20 }}
            animate={{ opacity: 1, scale: 1, y: 0 }}
            exit={{ opacity: 0, scale: 0.95, y: 20 }}
            transition={{
              duration: duration.normal / 1000,
              ease: motionEasing.spring,
            }}
            onClick={handleContentClick}
            role="dialog"
            aria-modal="true"
            aria-labelledby="confirm-title"
          >
            <ModalHeader>
              <ModalTitle id="confirm-title">{title}</ModalTitle>
              <CloseButton onClick={onCancel} aria-label="关闭">
                <FiX size={20} />
              </CloseButton>
            </ModalHeader>
            <ModalBody>{message}</ModalBody>
            <ModalFooter>
              <Button onClick={onCancel}>{cancelText}</Button>
              <Button $variant={confirmVariant} onClick={onConfirm}>
                {confirmText}
              </Button>
            </ModalFooter>
          </ModalContent>
        </ModalBackdrop>
      )}
    </AnimatePresence>
  );
};

export default ConfirmDialog;
